package com.wang.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.exception.BusinessException;
import com.wang.reponse.UpvoteVo;
import com.wang.user.model.Post;
import com.wang.user.model.Upvote;
import com.wang.user.model.User;
import com.wang.user.service.PostService;
import com.wang.user.service.UpvoteService;
import com.wang.user.mapper.UpvoteMapper;
import com.wang.user.service.user.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
* @author bkty0
* @description 针对表【upvote(帖子点赞表)】的数据库操作Service实现
* @createDate 2025-04-23 10:39:21
*/
@Service
public class UpvoteServiceImpl extends ServiceImpl<UpvoteMapper, Upvote>
    implements UpvoteService{

    @Resource
    private UpvoteMapper upvoteMapper;

    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    @Override
    public Boolean submit(Upvote upvote) {
        Post post = postService.getById(upvote.getPostId());
        if(ObjectUtil.isNull(post)){
            throw new BusinessException("帖子数据不存在");
        }
        User loginUser = userService.getLoginUser();
        Upvote upvote1 = getByPostIdAndUserId(post.getId(), loginUser.getUid());
        if(ObjectUtil.isNotNull(upvote1)){
            throw new BusinessException("已点赞，请勿重复点赞");
        }
        upvote.setUserId(loginUser.getUid());
        return save(upvote);
    }

    @Override
    public Boolean cancel(Upvote upvote) {
        Post post = postService.getById(upvote.getPostId());
        if(ObjectUtil.isNull(post)){
            throw new BusinessException("帖子数据不存在");
        }
        User loginUser = userService.getLoginUser();
        LambdaQueryWrapper<Upvote> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Upvote::getPostId,upvote.getPostId());
        lambdaQueryWrapper.eq(Upvote::getUserId,loginUser.getUid());
        return remove(lambdaQueryWrapper);
    }

    @Override
    public List<UpvoteVo> postUpvoteCountByPostIds(List<Long> postIds) {
        if(ObjectUtil.isEmpty(postIds)){
            return Collections.emptyList();
        }
        return upvoteMapper.postUpvoteCountByPostIds(postIds);
    }

    /**
     *
     * @param id 帖子id
     * @param uid
     * @return
     */
    @Override
    public Upvote getByPostIdAndUserId(Long id, Integer uid) {
        LambdaQueryWrapper<Upvote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Upvote::getPostId,id);
        queryWrapper.eq(Upvote::getUserId,uid);
        return getOne(queryWrapper);
    }
}




